package com.example.gobang_web_system.api;

import com.example.gobang_web_system.model.User;
import com.example.gobang_web_system.model.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
public class UserAPI {

    @Autowired
    private UserMapper userMapper;

    @PostMapping("/login")
    @ResponseBody
    public Object login(String username, String password, HttpServletRequest req) {
        // 根据 username 去数据库中查询
        // 如果找到匹配的用户&密码也一致，就认为登陆成功
        User user = userMapper.selectByName(username);
        System.out.println("[login] username=" + username);
        if(user == null || !user.getPassword().equals(password)) {
            // 登录失败
            System.out.println("登陆失败，用户名或密码错误，请重新登录！");
            return new User();
        }
        // 从请求中获取，如果有session会话，直接使用，如果没有，创建会话
        HttpSession httpSession = req.getSession(true);
        httpSession.setAttribute("user", user);
        return user;
    }

    @PostMapping("/register")
    @ResponseBody
    public Object register(String username, String password) {
        try {
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            userMapper.insert(user); // 调用插入方法
            System.out.println("[register] username=" + username);
            return user;
        } catch (org.springframework.dao.DuplicateKeyException e) {
            // 如果创建对象重复，捕获到异常，返回一个空的对象
            User user = new User();
            return user;
        }
    }

    @GetMapping("/userinfo")
    @ResponseBody
    public Object getUserInfo(HttpServletRequest req) {
        // 获取登陆状态，从中拿出登录对象状态
        try {
            HttpSession httpSession = req.getSession(false);
            // 之前set了什么，就get到对应用户信息
            User user = (User) httpSession.getAttribute("user");
            // 拿着这个 uesr 对象，去数据库中找，找到最新的数据
            User newUser = userMapper.selectByName(user.getUsername());
            return newUser;
        } catch (NullPointerException e) {
            // 如果拿到的会话为空，处理空指针异常
            return new User();
        }
    }
}
